package com.ciwong.epaper.modules.evaluate.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.Toast;

import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.SentenceAnswerBean;
import com.ciwong.epaper.modules.evaluate.bean.SentencesDetail;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.modules.pad.homeworkwidget.widget.remoteviews.GradeRemoteViews;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.epaper.widget.evaluate.SentenceSpeechView;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.oralevaluate.IEvaluateEngine;
import com.ciwong.libs.oralevaluate.OnEvaluateListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.oralevaluate.yunzhisheng.YZSEngine;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.unisound.edu.oraleval.sdk.sep15.IOralEvalSDK;
import com.unisound.edu.oraleval.sdk.sep15.SDKError;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by lzr on 2017/4/10.
 */
public class SpeechPlayController implements OnEvaluateListener {

    // 播放状态动画控件
    protected PlayStateView stateView;

    protected Context mContext;

    public static final String TAG = "SpeechPlayController";

    /**
     * 逐句跟读
     */
    public static final int LISTENER_MODE_ZHUJU = 1;


    /**
     * 独立通读
     */
    public static final int LISTENER_MODE_DULI = 11;

    /**
     * 年级id
     */
    private int mGradeId;

    /**
     * 选段背诵
     */
    public static final int LISTENER_MODE_XUANDUAN = 21;

    // 标记旁白音频录音的提示音
    public static final String ASIDE_AUDIO_TAG = "asideTag";

    // 开始录音
    public static final String ASIDE_AUDIO_TAG_EVALUATE = "pcm";

    /**
     * 封装好的一个接口里面有云之声的sdk 录音 等等
     */
    protected IEvaluateEngine iEvaluateEngine;

    // 设置短语标题
    private String sentenceText;

    private long startTime;

    public String uuid = UUID.randomUUID().toString();

    public ArrayList<Sentence> sentences = new ArrayList<Sentence>();

    protected Handler mHandler = new Handler();

    // 单词播放时长 用于录音与结束录音
    protected long audioDuration;

    // 单词播放时长 用于录音与结束录音
    protected long audioPlayDuration;

    // 录音增加的时长
    protected static final int RECORD_ADD_DURATION = 2000;

    // 播放增加的时长
    private int PLAY_ADD_DURATION = 150;

    // 显示句子控件
    protected SentenceSpeechView speechView;

    // 当前播放句子的下标
    protected int currentListenAndRepeatIndex;

    private int tempIndex;

    // 当前跟读的句子
    protected Sentence curSentence;

    /**
     * 是否播放评价语,设置先关后面这个要移交到父类中
     */
    protected boolean isPlayAssess = true;//

    /**
     * 播放流程的接口 方便在调用类中回调
     */
    protected SpeechPlayInterFace speechPlayInterFace;

    /**
     * 操作模式：逐句跟读、选段背诵、独立通读、单词跟读
     */
    protected int readMode;

    /**
     * 暂停
     */
    protected boolean isPause = true;

    private ArrayList<SentenceAnswerBean> sentenceAnswers = new ArrayList<>();

    // 是否重读
    private boolean isStress = false;

    // 录音的线程
    private MyThread myThread;

    // 下一步的线程
    private MyNextThread myNextThread;

    // 返回结果的线程
    private MyResultThread myResultThread;

    private boolean isSoundToLow = true;

    public boolean isContinueFromRecord = false;// 是否来自作业记录

    public int showSoundDetectTipsIndex = 0;// 要提示音量太小的索引

    private long userId = 0;

    protected boolean isInSentenceAll = false;// 是否是 全文阅读

    // 是否手动模式
    public boolean mIsUnAutoMode = false;

    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;

    public boolean ismIsUnAutoMode() {
        return mIsUnAutoMode;
    }

    public void setmIsUnAutoMode(boolean mIsUnAutoMode) {
        this.mIsUnAutoMode = mIsUnAutoMode;
    }

    public boolean isInSentenceAll() {
        return isInSentenceAll;
    }

    public void setInSentenceAll(boolean inSentenceAll) {
        isInSentenceAll = inSentenceAll;
    }

    public void setStress(boolean stress) {
        isStress = stress;
    }

    public boolean isStress() {
        return isStress;
    }

    public void setCurrentListenAndRepeatIndex(int currentListenAndRepeatIndex) {
        if (currentListenAndRepeatIndex > -1
                && currentListenAndRepeatIndex < sentences.size()) {
            curSentence = sentences.get(currentListenAndRepeatIndex);
        }
        this.currentListenAndRepeatIndex = currentListenAndRepeatIndex;
    }

    public void setTempIndex(int tempIndex) {
        this.tempIndex = tempIndex;
    }

    public void setSentenceAnswers(
            ArrayList<SentenceAnswerBean> sentenceAnswers) {
        this.sentenceAnswers = sentenceAnswers;
        if (this.sentenceAnswers != null) {
            currentListenAndRepeatIndex = this.sentenceAnswers.size();
        }
    }

    public ArrayList<SentenceAnswerBean> getSentenceAnswers() {
        return sentenceAnswers;
    }

    public void setPlayAssess(boolean playAssess) {
        isPlayAssess = playAssess;
    }

    public void setIsPause(boolean pause) {
        this.isPause = pause;
        if (isPause) {
            // 暂停状态
            AudioPlayer.getInstance().stop();
            if (iEvaluateEngine != null) {
                iEvaluateEngine.cancel();
            }
            speechView.closeStateIm(mIsUnAutoMode);
            if (myThread != null) {
                mHandler.removeCallbacks(myThread);
            }
            if (myNextThread != null) {
                mHandler.removeCallbacks(myNextThread);
            }
            if (myResultThread != null) {
                mHandler.removeCallbacks(myResultThread);
            }

        }
    }

    public void pauseStateChange() {
        if (tempIndex > currentListenAndRepeatIndex) {
            currentListenAndRepeatIndex = tempIndex;
            tempIndex = 0;
        }
    }

    public boolean isPause() {
        return isPause;
    }

    public SpeechPlayController() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O_MR1) {
            PLAY_ADD_DURATION = 200;
        } else {
            PLAY_ADD_DURATION = 100;
        }
    }

    /**
     * 构造函数
     *
     * @param speechView {@link SentenceSpeechView}
     * @param modeType
     */
    public SpeechPlayController(SentenceSpeechView speechView, int modeType,
                                String uuid, long startTime, boolean serviceExpired) {
        if (EApplication.getInstance().getClazz() != null) {
            mGradeId = EApplication.getInstance().getClazz().getGradeId();
        }
        this.readMode = modeType;
        this.mContext = speechView.getContext();
        this.speechView = speechView;
        this.startTime = startTime;
        this.serviceExpired = serviceExpired;
        iEvaluateEngine = new YZSEngine(mContext);
        if (mGradeId >= 1101 && mGradeId <= 1106) {
            iEvaluateEngine.SetScoreAdjuest(1.8f);
        } else {
            iEvaluateEngine.SetScoreAdjuest(1.7f);
        }
        iEvaluateEngine.setEvaluateListener(SpeechPlayController.this);
        if (uuid != null) {
            this.uuid = uuid;
        }

    }

    public void setSpeechPlayInterFace(SpeechPlayInterFace speechPlayInterFace) {
        this.speechPlayInterFace = speechPlayInterFace;
    }

    public int getCurrentListenAndRepeatIndex() {
        return currentListenAndRepeatIndex;
    }

    public ArrayList<Sentence> getSentences() {
        return sentences;
    }

    public void setSentences(ArrayList<Sentence> sentences) {
        this.sentences = sentences;
    }

    /**
     * 设置句子列表
     *
     * @param sentencesDetails
     * @param versionId
     * @param saveUuid
     * @param speech
     * @param userId
     * @return
     */
    public boolean setParagraphText(List<SentencesDetail> sentencesDetails,
                                    String versionId, String saveUuid, PlayStateView speech,
                                    ImageView playIocn, long userId, boolean isAddSentences) {
        this.stateView = speech;
        this.sentenceText = StringUtils.md5(versionId);
        if (!TextUtils.isEmpty(saveUuid)) {
            // uuid = saveUuid;
        }
        if (sentences == null) {
            sentences = new ArrayList<Sentence>();
        }
        for (SentencesDetail sentencesDetail : sentencesDetails) {
            Sentence sentence = new Sentence();
            sentence.setTextId(sentencesDetail.getVersionId());

            String name = sentencesDetail.getName().trim();
            sentence.setSentenceMp3(sentencesDetail.getAudioUrl());
            sentence.setImgUrl(sentencesDetail.getImgUrl());
            String replaceEvaluateText = SpeechUtils.replaceEvaluateText(name);
            String replaceAsSpace_str = SpeechUtils
                    .replaceAsSpace(replaceEvaluateText);
            String[] words = replaceAsSpace_str.split(" |…");
            if (null != sentencesDetail.getAnswer() && !"".equals(sentencesDetail.getAnswer())) {
                sentence.setAnswer(sentencesDetail.getAnswer().trim());
            } else {
                sentence.setAnswer("");
            }
            sentence.setText(name);
            List<WordDetail> wordDetails = new ArrayList<WordDetail>();
            int wordsLength = words.length;
            for (int z = 0; z < wordsLength; z++) {
                WordDetail wordDetail = new WordDetail();
                String text = words[z];
                wordDetail.setText(text);
                wordDetail.setColor(mContext.getResources()
                        .getColor(R.color.default_text_color));
                wordDetails.add(wordDetail);
            }
            sentence.setWordDetails(wordDetails);
            if (!TextUtils.isEmpty(sentencesDetail.getTranslate())) {
                sentence.setTranslate(sentencesDetail.getTranslate());
            }
            if (sentencesDetail.getStart() != null
                    && sentencesDetail.getStart().trim() != "") {
                try {
                    sentence.setStart(Integer
                            .parseInt(sentencesDetail.getStart().trim()));
                } catch (Exception e) {
                    CWLog.e("byou", "sentencesDetail.getStart()转换出错。。。");
                    e.printStackTrace();
                }
            }
            if (sentencesDetail.getDuration() != null
                    && sentencesDetail.getDuration().trim() != "") {
                try {
                    sentence.setDuration(Integer
                            .parseInt(sentencesDetail.getDuration().trim()));
                } catch (Exception e) {
                    CWLog.e("byou", "sentencesDetail.getDuration()转换出错。。。");
                    e.printStackTrace();
                }
            }
            if (isAddSentences) {
                sentences.add(sentence);
            }
        }
        bindSentenceData();
        if (speechView != null) {
            speechView.setFillblank(readMode == LISTENER_MODE_XUANDUAN);
            speechView.setSentences(sentences, speech, playIocn, userId,serviceExpired);
        }
        return true;
    }

    /**
     *
     */
    private void bindSentenceData() {
        if (this.sentenceAnswers != null && sentences != null
                && this.sentenceAnswers.size() <= sentences.size()) {
            for (int i = 0; i < this.sentenceAnswers.size(); i++) {
                sentences.set(i, sentenceAnswers.get(i).getSentence());
            }
        }
    }

    /**
     * 刷新界面显示
     *
     * @param isPlayState
     */
    public void refreshSpeechView(boolean isPlayState) {
        if (speechView != null) {
            speechView.addSentenceToView(currentListenAndRepeatIndex,
                    isPlayState, false, false, serviceExpired);
        }
    }

    public void refreshAllSpeechView(boolean isPlayState) {
        if (speechView != null) {
            speechView.addSentenceToView(currentListenAndRepeatIndex,
                    isPlayState);
        }
    }

    /**
     * 开始跟读
     *
     * @return
     */
    public boolean start() {
        speechView.toTop();
        if (currentListenAndRepeatIndex < sentences.size()) {
            play();
            return true;
        } else {
            return false;
        }
    }

    /**
     * 开始跟读或朗读
     */
    public void play() {
        curSentence = sentences.get(currentListenAndRepeatIndex);
        playWord(currentListenAndRepeatIndex, true);
    }

    // 播放音频的具体代码
    protected void playWord(int index, final boolean autoPlay) {
        if (isPause) {
            return;
        }
        Sentence sentence = sentences.get(index);

        String url = ESystem.formatPath(sentence.getSentenceMp3());
        if (url == null) {
            url = "";
        }
        if (sentence.getStart() > 0 || sentence.getDuration() > 0) {
            AudioPlayer.getInstance().setOnPlayListener(listener).play(url,
                    autoPlay, sentence.getStart(), (sentence.getDuration()
                            + sentence.getStart() + PLAY_ADD_DURATION));
            getPlayTime((sentence.getDuration() + PLAY_ADD_DURATION), url);
        } else {
            AudioPlayer.getInstance().setOnPlayListener(listener).play(url,
                    autoPlay);
        }
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M
                    && EApplication.getInstance().mPlayerspeed != 1.0f) {
                MediaPlayer mMediaPlayer = AudioPlayer.getInstance()
                        .getMediaPlayer();
                if (mMediaPlayer != null) {
                    try {
                        PlaybackParams params = mMediaPlayer.getPlaybackParams()
                                .setSpeed(EApplication
                                        .getInstance().mPlayerspeed);
                        if (params != null) {
                            mMediaPlayer.setPlaybackParams(params);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sentence.getDuration() > 0) {
            long subDuration = (long) (sentence.getDuration() * 0.5);
            audioDuration = sentence.getDuration()
                    + (subDuration > RECORD_ADD_DURATION ? subDuration
                    : RECORD_ADD_DURATION);
            audioPlayDuration = sentence.getDuration();
        }
        if (mIsUnAutoMode) {
            speechView.playUnAto(true);
        } else {
            speechView.play(audioPlayDuration + PLAY_ADD_DURATION);
        }
    }

    // 播放控制器的监听 包括句子播放完成的后续操作
    protected OnPlayListener listener = new OnPlayListener() {

        @Override
        public void stop(final Object mp3) {
            if (isPause) {
                return;
            }

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    stopOrStartPlay(mp3);
                }
            });
        }

        @Override
        public void onReadPlayer(long duration, Object mp3) {
            long curDuration = duration;
            if (curSentence != null && curSentence.getDuration() > 0) {
                curDuration = curSentence.getDuration() + PLAY_ADD_DURATION;
            }
            getPlayTime(curDuration, mp3);
        }

        @Override
        public void onPlayStart(Object o) {

        }

        @Override
        public void onPlaying(long duration, long progressSource) {
            long max = duration;
            long progress = progressSource;
            if (curSentence != null && curSentence.getDuration() > 0) {
                max = curSentence.getDuration() + PLAY_ADD_DURATION;
                progress = progress - curSentence.getStart();
            }
            speechView.updatePlayProgress(max, progress);
        }

        @Override
        public void onBuffer(Object o, long l, long l1) {

        }

        @Override
        public void onError(int i, Object tag) {
            playError(tag);
        }
    };

    protected void playError(Object tag) {
        if (!"pcm".equals(tag + "")) {
            // 设置为10秒
            audioDuration = 10000;
            audioPlayDuration = 10000;
            if (iEvaluateEngine != null) {
                iEvaluateEngine.cancel();
            }
            if (readMode == LISTENER_MODE_ZHUJU) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        speechView.closeStateIm(mIsUnAutoMode);
                        Toast toast = Toast.makeText(mContext, "播放音频失败",
                                Toast.LENGTH_SHORT);
                        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                        toast.show();
                    }
                });
            }
            AudioPlayer.getInstance().stop();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // 播放提示音
                    startRecordHint(currentListenAndRepeatIndex);
                }
            }, 2000);
        }
    }

    /**
     * 获取播放时间
     */
    protected void getPlayTime(long duration, Object mp3) {
        if (ASIDE_AUDIO_TAG.equals(mp3)) {
            return;
        }
        // 获取播放单词时长
        if (!"pcm".equals(mp3 + "")) {
            if (duration <= 0) {
                audioDuration = 10000;
                audioPlayDuration = 10000;
            } else {
                long subDuration = (long) (duration * 0.5);
                audioDuration = duration
                        + (subDuration > RECORD_ADD_DURATION ? subDuration
                        : RECORD_ADD_DURATION);
                audioPlayDuration = duration;
            }
        }
    }

    /**
     * 播放完成之后的流程
     */
    protected void stopOrStartPlay(Object mp3) {
        // 如果播放的是一个提示音说明是要开始录音了
        if (ASIDE_AUDIO_TAG.equals(mp3)) {
            // 录音
            showgetRecordPermissDialog();
            //record();
            return;
        }

        // 评价语播放结束
        if (ASIDE_AUDIO_TAG_EVALUATE.equals(mp3)) {
            if (speechPlayInterFace != null) {
                if (currentListenAndRepeatIndex < sentenceAnswers.size()) {
                    speechPlayInterFace.addResult(
                            sentenceAnswers.get(currentListenAndRepeatIndex),
                            currentListenAndRepeatIndex);
                }
                if (!mIsUnAutoMode) {
                    speechPlayInterFace.lastRecord(currentListenAndRepeatIndex,
                            sentences.size());
                }
            }
            if (!mIsUnAutoMode) {
                playNext();
            }
            return;
        }
        if (mIsUnAutoMode) {
            speechView.playUnAto(false);
            if (null != sentenceAnswers) {
                //有答案播放音频不直接录音
                if (sentenceAnswers.size() <= currentListenAndRepeatIndex || isStress) {
                    startRecordHint(currentListenAndRepeatIndex);
                }
            }
        } else {
            // 原音播放完成之后需要播放提示音
            startRecordHint(currentListenAndRepeatIndex);
        }
        //startRecordHint(currentListenAndRepeatIndex);
    }

    private CWDialog getRecordPermissDialog;

    /**
     * 获取Record权限提示框
     */
    private boolean showgetRecordPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(mContext, Manifest.permission.RECORD_AUDIO);
        if (isHavePermiss) {
            checkRecordAudioPermiss();
        } else {
            if (getRecordPermissDialog == null) {
                getRecordPermissDialog = new CWDialog(mContext);
                getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                getRecordPermissDialog.setMessage(mContext.getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        checkRecordAudioPermiss();
                    }
                });
                getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        if (mContext instanceof SentenceRepeatActivity) {
                            ((SentenceRepeatActivity) mContext).stopImg(true);
                        }

                    }
                });
            }
            getRecordPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用录音，判断权限
     */
    public boolean checkRecordAudioPermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && mContext.getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.RECORD_AUDIO);
            noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
            XXPermissionTool.checkPermissions((Activity) mContext, //
                    permissionList, //
                    noteMap, //
                    SentenceRepeatActivity.CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                record();
                            }
                        }
                    });
        } else {
            record();
        }
        return true;
    }

    /**
     * 开始录音提示音
     *
     * @param index 下标
     */
    public void startRecordHint(final int index) {

        try {
            if (index >= sentences.size()) {
                return;
            }
            if (curSentence == null) {
                curSentence = sentences.get(index);
            }
            AudioPlayer.getInstance().setOnPlayListener(listener).play(
                    R.raw.repeat_read_start_record, mContext, ASIDE_AUDIO_TAG);
        } catch (NullPointerException e) {
            e.getStackTrace();
        }

    }

    /**
     * 获取录音的地址
     *
     * @param sentence
     * @return
     */
    private File getSoundPath(Sentence sentence, int index) {
        return new File(ESystem.getAnswersUserIdMediaPathSentence(uuid),
                uuid + StringUtils.md5(sentence.getText()) + "&" + startTime
                        + EConstants.AUDIO_DEFAULT_SUFFIX);
    }

    /**
     * 获取录音Opus的地址
     *
     * @param sentence
     * @return
     */
    private File getSoundOpusPath(Sentence sentence, int index) {
        return new File(ESystem.getAnswersUserIdMediaOpusPathSentence(uuid),
                uuid + StringUtils.md5(sentence.getText()));
    }


    /**
     * 录音
     */
    protected void record() {
        try {
            if (isPause) {
                return;
            }
            Sentence sentence = sentences.get(currentListenAndRepeatIndex);
            String sentenceText = sentence.getText();
            // String processText =
            // SpeechUtils.replaceEvaluateText(sentenceText);
            String processText = SpeechUtils.replaceEvaluateText(sentenceText);
            processText = SpeechUtils.replaceAsSpace(processText);
            iEvaluateEngine.setText(processText);
            iEvaluateEngine.setConnectTimeout(30000);
            // 音频文件地址
            iEvaluateEngine.setRecordPath(
                    getSoundPath(sentence, currentListenAndRepeatIndex)
                            .getAbsolutePath());
            // 音频opus文件地址
            iEvaluateEngine.SetOpusPath(
                    getSoundOpusPath(sentence, currentListenAndRepeatIndex)
                            .getAbsolutePath());

            // 开始录音语句
            if (audioDuration <= 0) {
                int wordTime = processText.length() * 400;
                audioDuration = wordTime;
            }
            speechView.startRecord(audioDuration, mIsUnAutoMode);
            UserInfoBase userInfoBase = EApplication.getInstance()
                    .getUserInfoBase();
            if (null != userInfoBase) {
                iEvaluateEngine
                        .setUid(String.valueOf(userInfoBase.getUserId()));
            }

            // 设置相关配置
            iEvaluateEngine.start("C");
            if (speechPlayInterFace != null) {
                speechPlayInterFace.startRecord();
            }
            myThread = new MyThread();
            mHandler.postDelayed(myThread, audioDuration);
        } catch (OutOfMemoryError error) {
            error.getStackTrace();
        }

    }

    /**
     * /** 停止录音
     */
    public void stopRecord() {
        mHandler.removeCallbacks(myThread);
        if (!(iEvaluateEngine.getiOralEvalSDKStatus() == 4 || iEvaluateEngine.getiOralEvalSDKStatus() == 5)) {
            if (mContext instanceof SentenceRepeatActivity) {
                ((SentenceRepeatActivity) mContext).showCricleProgress(" 评分中...");
            }
        }
        iEvaluateEngine.stop();
        if (speechPlayInterFace != null) {
            speechPlayInterFace.stopRecord();
        }
    }

    public void loading(Context context, boolean isLoading) {
        GradeRemoteViews gradeRemoteViews = new GradeRemoteViews(context);
        if (isLoading) {

            gradeRemoteViews.loading();

        } else {
            gradeRemoteViews.loadComplete();
        }

    }

    /**
     * /** 停止录音
     */
    public void cancelRecord() {
        mHandler.removeCallbacks(myThread);
        iEvaluateEngine.cancel();
        if (speechPlayInterFace != null) {
            speechPlayInterFace.stopRecord();
        }
    }

    protected void playNext() {
        // 延迟一秒给用户一秒的时间
        myNextThread = new MyNextThread();
        mHandler.postDelayed(myNextThread, 1000);
    }

    // -------------OnEvaluateListener接口定义的方法--------------------

    @Override
    public void onInit(int var1) {
        CWLog.d(TAG, "OnEvaluateListener onInit:" + var1);
    }

    @Override
    public void onError(IOralEvalSDK iOralEvalSDK, SDKError sdkError,
                        IOralEvalSDK.OfflineSDKError offlineSDKError) {
        CWLog.d(TAG, "OnEvaluateListener onError:IOralEvalSDK" + sdkError);
        SDKError.Category category = sdkError.category;
        if (mContext instanceof SentenceRepeatActivity) {
            ((SentenceRepeatActivity) mContext).hideCricleProgress();
        }
        if (SDKError.Category.Device != category) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        tempIndex = currentListenAndRepeatIndex;
                        EvaluateResult eResult = new EvaluateResult();
                        //评分失败 设置分数为-1
                        eResult.setScore(-1);
                        String lines = JsonParserUtil.toJson(eResult);
                        // 把结果添加到结果结合中去,音频文件地址
                        StringBuffer sb = new StringBuffer(ALiYunManager.ACCESS_URL);
                        sb.append("work/followread/" + CWUtils.getReadTime(startTime) + "/"
                                + CWSys.getSharedLong(
                                BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0)
                                + "/");
                        curSentence.setScore((int) eResult.getScore());
                        curSentence.setIntegrity(0);
                        curSentence.setFluency(0);
                        curSentence.setPronunciation(0);
                        curSentence.setSoundUrl(getSoundPath(curSentence,
                                currentListenAndRepeatIndex)
                                .getAbsolutePath());
                        sb.append(uuid + StringUtils.md5(curSentence.getText()) + "&" + startTime);
                        sb.append(EConstants.AUDIO_DEFAULT_SUFFIX);

                        SentenceAnswerBean mSentenceAnswerBean = new SentenceAnswerBean(
                                curSentence,
                                getSoundPath(curSentence,
                                        currentListenAndRepeatIndex)
                                        .getAbsolutePath(),
                                (int) (audioDuration), lines, sb.toString(), "", eResult.getFluency(), eResult.getIntegrity(), eResult.getPronunciation());
                        speechPlayInterFace.setRecordStatus(false);
                        if (isStress) {
                            sentenceAnswers.set(currentListenAndRepeatIndex,
                                    mSentenceAnswerBean);
                            // 重读接口
                            currentListenAndRepeatIndex = sentences.size() - 1;
                        } else {
                            if (currentListenAndRepeatIndex < sentenceAnswers
                                    .size()) {
                                sentenceAnswers.set(currentListenAndRepeatIndex,
                                        mSentenceAnswerBean);
                            } else {
                                sentenceAnswers.add(mSentenceAnswerBean);
                            }
                        }
                        tempIndex++;

                        myResultThread = new MyResultThread();
                        myResultThread.setEResult(eResult);
                        myResultThread.setScore(-1);
                        myResultThread.setmSentenceAnswerBean(mSentenceAnswerBean);
                        if (mIsUnAutoMode) {
                            mHandler.postDelayed(myResultThread, 0);
                        } else {
                            if (currentListenAndRepeatIndex == (sentences.size()
                                    - 1) || isStress) {
                                mHandler.postDelayed(myResultThread, 2000);
                            } else {
                                mHandler.postDelayed(myResultThread, 1000);
                            }
                        }
                    } catch (
                            Exception e) {
                        e.getStackTrace();
                    }
                }
            });
        }
        if (speechPlayInterFace != null) {
            speechPlayInterFace.recError(iOralEvalSDK, sdkError,
                    offlineSDKError);
        }
    }

    @Override
    public void onStart() {
        CWLog.d(TAG, "OnEvaluateListener onStart()");
    }

    @Override
    public void onVolume(int rms) {
        if (rms > 40) {
            isSoundToLow = false;
        }
    }

    @Override
    public void onStop(final int i, final EvaluateResult eResult, final String url) {
        CWLog.d(TAG, "OnEvaluateListener onStop:" + i);
        if (mContext instanceof SentenceRepeatActivity) {
            ((SentenceRepeatActivity) mContext).hideCricleProgress();
        }
        if (eResult == null) {
            onError(null, new SDKError(SDKError.Category.Server, -9999, null),
                    null);
            CWLog.d(TAG, "评测错误  结果为空=onError(-100)");
            return;
        }
        // 优化评分结果
        eResult.setScore(SpeechUtils.scoreOptimize(eResult.getScore()));
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    if (i == -2) {// 报错了停止录音刷新界面
                    }
                    tempIndex = currentListenAndRepeatIndex;
                    final int score = (int) eResult.getScore();

                    speechView.showResult(eResult, curSentence, false, serviceExpired);

                    String lines = JsonParserUtil.toJson(eResult);
                    // 把结果添加到结果结合中去,音频文件地址
                    StringBuffer sb = new StringBuffer(ALiYunManager.ACCESS_URL);
                    sb.append("work/followread/" + CWUtils.getReadTime(startTime) + "/"
                            + CWSys.getSharedLong(
                            BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0)
                            + "/");
                    curSentence.setScore((int) eResult.getScore());
                    curSentence.setIntegrity(eResult.getIntegrity());
                    curSentence.setFluency(eResult.getFluency());
                    curSentence.setPronunciation(eResult.getPronunciation());
                    curSentence.setSoundUrl(getSoundPath(curSentence,
                            currentListenAndRepeatIndex)
                            .getAbsolutePath());
                    sb.append(uuid + StringUtils.md5(curSentence.getText()) + "&" + startTime);
                    sb.append(EConstants.AUDIO_DEFAULT_SUFFIX);

                    SentenceAnswerBean mSentenceAnswerBean = new SentenceAnswerBean(
                            curSentence,
                            getSoundPath(curSentence,
                                    currentListenAndRepeatIndex)
                                    .getAbsolutePath(),
                            (int) (audioDuration), lines, sb.toString(), url, eResult.getFluency(), eResult.getIntegrity(), eResult.getPronunciation());
                    //录音时长清零
                    audioDuration = 0;
                    if (mIsUnAutoMode) {
                        speechPlayInterFace.scoreResult(score, eResult.getIntegrity(), eResult.getFluency(), eResult.getPronunciation(), mSentenceAnswerBean);
                    } else {
                        speechPlayInterFace.scoreResult(score, eResult.getIntegrity(), eResult.getFluency(), eResult.getPronunciation(), mSentenceAnswerBean);
                        speechPlayInterFace.setRecordStatus(false);
                    }
                    // 如果是最后一个或者是重读都要延迟2秒 用来显示分数用
                    if (isStress) {
                        sentenceAnswers.set(currentListenAndRepeatIndex,
                                mSentenceAnswerBean);
                        // 重读接口
                        currentListenAndRepeatIndex = sentences.size() - 1;
                    } else {
                        if (currentListenAndRepeatIndex < sentenceAnswers
                                .size()) {
                            sentenceAnswers.set(currentListenAndRepeatIndex,
                                    mSentenceAnswerBean);
                        } else {
                            sentenceAnswers.add(mSentenceAnswerBean);
                        }
                    }
                    tempIndex++;
                    myResultThread = new MyResultThread();
                    myResultThread.setEResult(eResult);
                    myResultThread.setScore(score);
                    myResultThread.setmSentenceAnswerBean(mSentenceAnswerBean);
                    // 声音过低且分数低于80时给予提示

                    if ((readCount <= 3 && score < 80 && isSoundToLow)) {
                        ToastUtil.INSTANCE.toastCenter(mContext,
                                R.string.read_sound_too_low_tips,
                                R.mipmap.ic_increase_volume);
                    }
                    CWLog.e(TAG, "score retryscore2: "
                            + currentListenAndRepeatIndex);
                    isSoundToLow = true;
                    if (mIsUnAutoMode) {
                        mHandler.postDelayed(myResultThread, 0);
                    } else {
                        if (currentListenAndRepeatIndex == (sentences.size()
                                - 1) || isStress) {
                            mHandler.postDelayed(myResultThread, 2000);
                        } else {
                            mHandler.postDelayed(myResultThread, 1000);
                        }
                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }

            }
        });
    }

    public static int readCount = 0;

    // 录音结束后回调
    @Override
    public void onStartOralEval() {
        readCount++;
        CWLog.e(TAG, "OnEvaluateListener onStartOralEval:句子" + readCount);
    }

    /**
     * 播放评价语音、进行下一个单词
     *
     * @param eResult
     * @param score
     */
    private void playAfd(EvaluateResult eResult, int score) {
        if (isPlayAssess) {
            playResultScore(score);
        } else {
            // 不播放评价语那么这个地方就要走下一个流程了啊
            if (speechPlayInterFace != null) {
                speechPlayInterFace.addResult(
                        sentenceAnswers.get(currentListenAndRepeatIndex),
                        currentListenAndRepeatIndex);
            }
            if (!mIsUnAutoMode) {
                speechPlayInterFace.lastRecord(currentListenAndRepeatIndex,
                        sentences.size());
                playNext();
            }
        }
    }

    /**
     * 暂停之后的调用
     */
    public void paseReuslt() {
        if (speechPlayInterFace != null) {
            speechPlayInterFace.addResult(
                    sentenceAnswers.get(currentListenAndRepeatIndex - 1),
                    currentListenAndRepeatIndex - 1);
            speechPlayInterFace.lastRecord(currentListenAndRepeatIndex - 1,
                    sentences.size());
        }
    }

    /**
     * 根据分数播放评价语
     *
     * @param score
     */
    protected void playResultScore(float score) {
        // 先注释状态
        // operateStatus = OPERATE_STATUS_COMPARISONING;
        // playStatus = PLAY_STATUS_PLYAING_4;

        // int raw = SpeechUtils.getResultSoundRaw(item_my_work_child_score);
        int raw = 0;
        if (score < SpeechUtils.SCORE_1) {
            // raw = isAreadyRepeat ? R.raw.a_level3
            // : SpeechUtils.getRandomRaw(SpeechUtils.LEVEL_A);
            // isAreadyRepeat = false;
            raw = SpeechUtils.getRandomRaw(SpeechUtils.LEVEL_A);
        } else if (score < SpeechUtils.SCORE_2) {
            raw = SpeechUtils.getRandomRaw(SpeechUtils.LEVEL_B);
        } else if (score < SpeechUtils.SCORE_3) {
            raw = SpeechUtils.getRandomRaw(SpeechUtils.LEVEL_C);
        } else if (score < SpeechUtils.SCORE_4) {
            raw = SpeechUtils.getRandomRaw(SpeechUtils.LEVEL_D);
        } else {
            raw = SpeechUtils.getRandomRaw(SpeechUtils.LEVEL_E);
        }
        AudioPlayer.getInstance().setOnPlayListener(listener).play(raw,
                mContext, ASIDE_AUDIO_TAG_EVALUATE);
    }

    public interface SpeechPlayInterFace {

        void nextPlay(int currentIndex, int count, boolean isPrevious);

        /**
         * 设置分数
         *
         * @param score
         */
        void scoreResult(int score, float integrity, float fluency, float pronunciation, SentenceAnswerBean mSentenceAnswerBean);

        void addResult(SentenceAnswerBean sentenceAnswerBean, int index);

        // 最后播放
        void lastRecord(int currentIndex, int count);

        void startRecord();

        void stopRecord();

        void recError(IOralEvalSDK evalSDK, SDKError sdkError,
                      IOralEvalSDK.OfflineSDKError offlineSDKError);

        void setResultScoreStatus(SentenceAnswerBean mAnswerRecorder);

        void setRecordStatus(Boolean isreaord);

    }

    class MyThread extends Thread {

        @Override
        public void run() {
            stopRecord();
        }
    }

    class MyNextThread extends Thread {

        @Override
        public void run() {
            if (currentListenAndRepeatIndex < (sentences.size() - 1)) {
                // 如果当前播放的下标还在句子列表中就继续播放下一个句子
                currentListenAndRepeatIndex++;
                if (currentListenAndRepeatIndex > (sentences.size())) {
                    return;
                }
                play();
                if (speechPlayInterFace != null) {
                    speechPlayInterFace.nextPlay(currentListenAndRepeatIndex,
                            sentences.size(), false);
                }
            }
        }
    }

    /**
     * 获取上传MP3 文件KEY
     *
     * @param uploadFilePath 上传文件路径
     * @return KEY
     */
    private String getMP3Key(String uploadFilePath) {
        return "work/followread/" + CWUtils.getReadTime(startTime) + "/" + CWSys
                .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/"
                + new File(uploadFilePath).getName();
    }

    class MyResultThread extends Thread {

        private EvaluateResult evaluateResult;

        private int score;

        private SentenceAnswerBean mSentenceAnswerBean;

        public void setEResult(EvaluateResult evaluateResult) {
            this.evaluateResult = evaluateResult;
        }

        public void setmSentenceAnswerBean(
                SentenceAnswerBean mSentenceAnswerBean) {
            this.mSentenceAnswerBean = mSentenceAnswerBean;
        }

        public void setScore(int score) {
            this.score = score;
        }

        @Override
        public void run() {
            playAfd(evaluateResult, score);
            // 设置录音播放按钮数据
            speechPlayInterFace.setResultScoreStatus(mSentenceAnswerBean);
        }
    }
}
